import { VuexModule, Module, Mutation, Action, getModule } from 'vuex-module-decorators'
import { RouteConfig } from 'vue-router'
import { constantRoutes, asyncRoutes } from '@/router'
import store from '@/store'
import { getMenu } from '@/api/user'
import { validatenull } from '@/utils/validate'
import Layout from '@/Layout/index.vue'
import Framework from '@/views/Framework.vue'
import { getStore, setStore, removeStore } from '@/utils/store'

// 将导入的路由与动态路由做过滤
const filterRoutes = (orgRoutes: RouteConfig[], routes: RouteConfig[]): RouteConfig[] => {
  orgRoutes.forEach(item => {

  })
  return []
}

const hasPermission = (roles: string[], route: RouteConfig) => {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

export function formatRoutes(aMenu: Array<any>): RouteConfig[] {
  // debugger
  const aRouter: RouteConfig[] = []
  // console.log('aMeun->', aMenu)
  aMenu.forEach(oMenu => {
    const {
      path,
      name,
      icon,
      children
    } = oMenu

    const component: string = 'Layout'
    if (!validatenull(component)) {
      if (path === null) {
        console.log('path', path)
        console.log('name', name)
        console.log('--------------------------------------')
      }

      const oRouter = {
        path: path,
        // component: Layout,
        name: name,
        meta: { title: name, icon: icon },
        children: validatenull(children) ? [] : formatRoutes(children)
      }
      aRouter.push(oRouter)
    }
  })

  return aRouter
}

export const filterAsyncRoutes = (routes: RouteConfig[], roles: string[]) => {
  const res: RouteConfig[] = []
  routes.forEach(route => {
    const r = { ...route }
    if (hasPermission(roles, r)) {
      if (r.children) {
        r.children = filterAsyncRoutes(r.children, roles)
      }
      res.push(r)
    }
  })
  return res
}

// 过滤路由，
/* export const filterRoutes = (routes: RouteConfig[]) => {
  routes.forEach((route, index) => {
    asyncRoutes.find(asyncRoute => {
      return
    })
  })
} */

export interface IPermissionState {
  routes: RouteConfig[] // 用于菜单渲染
  dynamicRoutes: RouteConfig[] // 读取进来的动态路由
}

@Module({ dynamic: true, store, name: 'permission' })
class Permission extends VuexModule implements IPermissionState {
  public routes: RouteConfig[] = []
  public dynamicRoutes: RouteConfig[] = getStore({ name: 'routes' }) || []

  @Mutation
  private SET_ROUTES(routes: RouteConfig[]) {
    this.routes = constantRoutes.concat(routes)
    this.dynamicRoutes = routes
  }

  @Mutation
  private REMOVE_ROUTES() {
    this.routes = []
    this.dynamicRoutes = []
  }

  @Action
  public GenerateRoutes(roles: string[]): Promise<any> {
    // 从本地把路由读取进来
    const routes: any = getStore({ name: 'routes' })
    // debugger
    if (routes) {
      // debugger
      this.SET_ROUTES(routes)
      return Promise.resolve()
    }

    // 从接口把菜单读取进来
    return getMenu().then(res => {
      /* const asyncRouterMap = formatRoutes(res.data)
      let accessedRoutes
      if (roles.includes('admin')) {
        accessedRoutes = asyncRouterMap
      } else {
        accessedRoutes = filterAsyncRoutes(asyncRouterMap, roles)
      } */
      const routeData = res.data
      let accessedRoutes = formatRoutes(routeData)
      // console.log(accessedRoutes)
      this.SET_ROUTES(accessedRoutes)
      // 将解析好的路由存在store中
      setStore({
        name: 'routes',
        content: accessedRoutes,
        type: 'session'
      })
      return Promise.resolve(accessedRoutes)
    })
  }

  @Action
  public removeRoutes() {
    this.REMOVE_ROUTES()
    removeStore({ name: 'routes' })
  }
}

export const PermissionModule = getModule(Permission)
